package com.ziroom.crm.mq.core.retry.delay;

import com.ziroom.crm.mq.core.retry.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>固定延迟重试</p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author WeiShaoying
 * @version 1.0
 * @date Created in 2020年09月08日 15:15
 * @since 1.0
 */
@NoArgsConstructor
@Slf4j
public class FixedDelayPolicy implements DelayPolicy {

    private Long sleep = 5000L;

    private final Sleeper sleeper = new ThreadSleeper();


    public FixedDelayPolicy(long sleepMilli) {
        this.sleep = sleepMilli;
    }

    @Override
    public DelayContext start(RetryContext retryContext) {
        return new FixedDelayContext(retryContext);
    }

    @Override
    public void delay(DelayContext delayContext) {
        // sleep 会占用线程资源，导致线程不能释放，间接导致吞吐量下降
        try {
            sleeper.sleep(sleep);
        } catch (InterruptedException e) {
            log.error("FixedDelayPolicy InterruptedException", e);
        }
    }

    @Override
    public long getDelayTime(DelayContext delayContext) {
        return sleep;
    }

    @Data
    private static class FixedDelayContext implements DelayContext {

        private static final long serialVersionUID = -1613469732760816934L;

        private RetryContext retryContext;

        public FixedDelayContext(RetryContext retryContext) {
            this.retryContext = retryContext;
        }
    }
}
